﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace GameViewer.Core.Plugins
{
    public class PluginHelper
    {
        public static List<T> GetPlugins<T>(string path)
        {
            string[] files = System.IO.Directory.GetFiles(path, "*.dll");
            List<T> list = new List<T>();
            System.Diagnostics.Debug.Assert(typeof(T).IsInterface);
            foreach (string file in files)
            {
                Assembly assembly = null;
                try
                {
                    assembly = Assembly.LoadFile(file);
                }
                catch
                { }

                foreach (Type type in assembly.GetTypes())
                {
                    if (!type.IsClass || type.IsNotPublic)
                        continue;

                    try
                    {
                        Type[] interfaces = type.GetInterfaces();
                        if(((IList<Type>)interfaces).Contains(typeof(T)))
                        {
                            T t = (T)Activator.CreateInstance(type);
                            list.Add(t);
                        }
                    }
                    catch
                    { }
                }                
            }
            return list;
        }
    }
}
